package com.xbenben.demo;


import org.junit.Test;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * xbenben
 * Date:2022/1/15 21:50
 **/
public class DateUtilDemo {


    public static void main(String[] args) throws Exception {

        String dateStr = "2021-6-23 23:12:11";
        String dateStr2 = "2021623";

        //Wed Jun 23 00:00:00 CST 2021
        Date dateFromStr = new SimpleDateFormat("yyyy-MM-dd ").parse(dateStr);
        //Wed Jun 23 23:12:11 CST 2021
        Date dateFromStr2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(dateStr);


        String yyyymMdd = new SimpleDateFormat("yyyy-MM-dd").format(dateFromStr);


        System.out.println(dateFromStr);
        System.out.println(dateFromStr2);
        System.out.println("-------");
        //解析为 long
        System.out.println(yyyymMdd);

    }


    @Test
    public void parsDateTolocalDate() {

        Date date = new Date();


        String format = new SimpleDateFormat("YYYYMMdd").format(date);

        System.out.println(format);


    }

    @Test
    public void parsDateTolocalDate1() {


        String yyyymMdd = new SimpleDateFormat("yyyyMMdd").format(20200112);


    }


    @Test
    public void time1() {
        try {
            String str = "20200828";


            SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
            formatter.setLenient(false);


            Date newDate = formatter.parse(str);
            formatter = new SimpleDateFormat("yyyy-MM-dd");

            String format = formatter.format(newDate);


            System.out.println(format);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
    //输出结果为：2020-08-28

    /**
     * 获取 时间 前几分钟
     */
    @Test
    public void time2() {


        long currentTimeM = System.currentTimeMillis();

        Date beginDate = new Date((currentTimeM - (60 * 5 * 1000)));
        Date endDate = new Date(currentTimeM);

        SimpleDateFormat sbf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        String beginTime = sbf.format(beginDate);
        String endTime = sbf.format(endDate);

        System.out.println(beginTime);
        System.out.println(endTime);


    }


}
